package com.sqx.modules.health.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.*;
import com.sqx.modules.health.service.*;
import com.sqx.modules.health.utils.StringUtil;
import com.sqx.modules.health.utils.UniHmacSHA256Util;
import com.sqx.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(value = "app端IM相关接口", tags = "app端IM相关接口", description = "")
@RestController
@RequestMapping("/health/app/im")
public class AppIMController {
    @Autowired
    private IUserService userService;

    /*@ApiOperation(value = "IM注册账户", notes = "IM注册账户,传formdata Model对象")
    @PostMapping("/getImToken")
    public Result imRegister(@RequestParam Map<String, String> params) {*/
    public Result imRegister(String uid, String appId) {

        /*String uid = params.get("uid");
        if (StrUtil.isBlank(uid)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }*/

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> uniIdTokenMap = new HashMap<>();

        SysUserEntity user = userService.getById(uid);
        if (!StringUtil.isEmpty(user.getImtoken())) {
            uniIdTokenMap.put("token", user.getImtoken());
            uniIdTokenMap.put("tokenExpired", user.getImtokenexpired());
            resultMap.put("token", user.getToken());
            resultMap.put("uniIdToken", uniIdTokenMap);
            return Result.success(resultMap);
        }

        String avatar = user.getAvatarUrl();
        String externalUid = user.getUserId() + "";
        Integer gender = user.getGender();
        String nickname = user.getNickName();
        long timestamp = System.currentTimeMillis();
        String nonce = "manbingyiliao";

        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("avatar", "https://lanchen-1316460328.cos.ap-nanjing.myqcloud.com/avatar.png");
        bodyMap.put("externalUid", externalUid);
        bodyMap.put("gender", gender);
        bodyMap.put("nickname", nickname);

        Map<String, Object> clientInfoMap = new HashMap<>();
        clientInfoMap.put("uniPlatform", "app");
        clientInfoMap.put("appId", appId);

        Map<String, Object> coludBodyMap = new HashMap<>();
        coludBodyMap.put("clientInfo", clientInfoMap);
        //coludBodyMap.put("uniIdToken", "");
        coludBodyMap.put("params", bodyMap);

        String signature = UniHmacSHA256Util.getSignature(bodyMap, nonce, timestamp);

        //链式构建请求
        String result2 = HttpRequest.post("https://fc-mp-6a09f23b-1c31-49bf-b6fa-fe97807d6a48.next.bspapp.com/uniIdCo/externalRegister")
                //头信息，多个头信息多次调用此方法即可
                .header("uni-id-nonce", nonce)
                .header("uni-id-timestamp", String.valueOf(timestamp))
                .header("uni-id-signature", signature)
                .header("Content-Type", "application/json")
                .header("Cache-Control", "no-cache")
                .body(JSON.toJSONString(coludBodyMap))
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result2);
        String errCode = jsonObject.getString("errCode");
        if ("0".equals(errCode)) {
            JSONObject newToken = jsonObject.getJSONObject("newToken");
            user.setImid(jsonObject.getString("uid"));
            user.setImtoken(newToken.getString("token"));
            user.setImtokenexpired(newToken.getLong("tokenExpired"));
            userService.saveOrUpdate(user);

            uniIdTokenMap.put("token", user.getImtoken());
            uniIdTokenMap.put("tokenExpired", user.getImtokenexpired());
            resultMap.put("token", user.getToken());
            resultMap.put("uniIdToken", uniIdTokenMap);
            return Result.success(resultMap);
        }

        return Result.success(result2);
    }

    @ApiOperation(value = "IM注册账户", notes = "IM注册账户,传formdata Model对象")
    @PostMapping("/imLogin")
    public Result imLogin(@RequestParam Map<String, String> params) {

        String uid = params.get("uid");
        String appId = params.get("appId");
        if (StrUtil.isBlank(uid) && StrUtil.isBlank(appId) ) {
            return Result.error(Constants.CODE_400, "参数错误");
        }

        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> uniIdTokenMap = new HashMap<>();

        SysUserEntity user = userService.getById(uid);

        String externalUid = user.getUserId() + "";
        long timestamp = System.currentTimeMillis();
        String nonce = "manbingyiliao";

        Map<String, Object> bodyMap = new HashMap<>();
        bodyMap.put("externalUid", externalUid);

        Map<String, Object> clientInfoMap = new HashMap<>();
        clientInfoMap.put("uniPlatform", "app");
        clientInfoMap.put("appId", appId);

        Map<String, Object> coludBodyMap = new HashMap<>();
        coludBodyMap.put("clientInfo", clientInfoMap);
        //coludBodyMap.put("uniIdToken", "");
        coludBodyMap.put("params", bodyMap);

        String signature = UniHmacSHA256Util.getSignature(bodyMap, nonce, timestamp);

        //链式构建请求
        String result2 = HttpRequest.post("https://fc-mp-6a09f23b-1c31-49bf-b6fa-fe97807d6a48.next.bspapp.com/uniIdCo/externalLogin")
                //头信息，多个头信息多次调用此方法即可
                .header("uni-id-nonce", nonce)
                .header("uni-id-timestamp", String.valueOf(timestamp))
                .header("uni-id-signature", signature)
                .header("Content-Type", "application/json")
                .header("Cache-Control", "no-cache")
                .body(JSON.toJSONString(coludBodyMap))
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result2);
        String errCode = jsonObject.getString("errCode");
        if ("0".equals(errCode)) {
            JSONObject newToken = jsonObject.getJSONObject("newToken");
            user.setImid(jsonObject.getString("uid"));
            user.setImtoken(newToken.getString("token"));
            user.setImtokenexpired(newToken.getLong("tokenExpired"));
            userService.saveOrUpdate(user);

            uniIdTokenMap.put("token", user.getImtoken());
            uniIdTokenMap.put("tokenExpired", user.getImtokenexpired());
            resultMap.put("token", user.getToken());
            resultMap.put("uniIdToken", uniIdTokenMap);
            return Result.success(resultMap);
        } else if ("uni-id-account-not-exists".equals(errCode)) {
            return imRegister(uid, appId);
        } else {
            return Result.success(result2);
        }
        //return Result.success(result2);
    }

}
